<template xmlns="http://www.w3.org/1999/html">
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.status" placeholder="状态" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option label="正常" value="1" />
        <el-option label="禁用" value="0" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加家族长
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <a class="click_a" href="javascript:;" onclick="drawer = true">{{ row.id }}</a>
        </template>
      </el-table-column>
      <el-table-column label="名称" min-width="120" align="center">
        <template slot-scope="{row}">
          <a href="javascript:;">{{ row.name }}</a>
        </template>
      </el-table-column>
      <el-table-column label="账号" min-width="120" align="center">
        <template slot-scope="{row}">
          <a href="javascript:;">{{ row.username }}</a>
        </template>
      </el-table-column>
      <el-table-column label="聊天收益" min-width="120" align="center">
        <template slot-scope="{row}">
          <a href="javascript:;">{{ row.chat_amount }}</a>
        </template>
      </el-table-column>
      <el-table-column label="礼物收益" min-width="120" align="center">
        <template slot-scope="{row}">
          <a href="javascript:;">{{ row.gift_rate }}</a>
        </template>
      </el-table-column>
      <el-table-column label="语聊收益" min-width="120" align="center">
        <template slot-scope="{row}">
          <a href="javascript:;">{{ row.voice_amount }}</a>
        </template>
      </el-table-column>
      <el-table-column label="余额" align="center">
        <template slot-scope="{row}">
          <span>{{ row.money }}</span>
        </template>
      </el-table-column>
      <el-table-column label="今日收益" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.last_login_ip }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <a class="click_a" @click="handleUpdate(row)">
            编辑
          </a>
          <a class="click_a" @click="getFirmMoneyLog(row)">
            收入
          </a>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <div class="components-container">
      <el-drawer
        v-drawerDrag
        :visible.sync="drawerVisibleMoney"
        size="1200px"
        title="余额日志"
      >
        <FirmMoneyList :firm_id.sync="currentFirmId" />
      </el-drawer>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="margin: 0 45px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item :label="dialogStatus==='create' ? '密码':'密码（不填不更改）'" prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="temp.status">
            <el-radio v-for="status in statusOptions" :label="status.key" border>
              {{ status.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="聊天收益（金额）" prop="chat_amount">
          <el-input v-model="temp.chat_amount" />
        </el-form-item>
        <el-form-item label="礼物收益（百分比）" prop="gift_rate">
          <el-input v-model="temp.gift_rate" />
        </el-form-item>
        <el-form-item label="语音收益（金额）" prop="voice_amount">
          <el-input v-model="temp.voice_amount" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { firmList, createFirm, updateFirm } from '@/api/firm'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import elDragDialog from '@/directive/el-drag-dialog'
import FirmMoneyList from '@/views/firmMoneyLog/list.vue'

export default {
  name: 'ComplexTable',
  components: { Pagination, FirmMoneyList },
  directives: { waves, elDragDialog },
  filters: {
    statusText(status) {
      const statusMap = {
        0: '禁用',
        1: '正常'
      }
      return statusMap[parseInt(status)]
    },
    formatTime: function(time) {
      if (parseInt(time) > 0) {
        return parseTime(parseInt(time), '{y}-{m}-{d} {h}:{i}')
      }
      return '-'
    },
    formatSex: function(sex) {
      const sexMap = {
        0: '未知',
        1: '男',
        2: '女'
      }
      return sexMap[parseInt(sex)]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        sort: 'desc',
        sort_field: 'id',
        status: ''
      },
      rules: {
        username: [{ required: true, message: '请输入账号', trigger: 'change' }],
        chat_amount: [{ required: true, message: '请输入聊天收益', trigger: 'change' }],
        gift_rate: [{ required: true, message: '请输入礼物收益', trigger: 'change' }],
        voice_amount: [{ required: true, message: '请输入语聊收益', trigger: 'change' }]
      },
      downloadLoading: false,
      drawerVisibleMoney: false,
      userInfo: {},
      dialogFormVisible: false,
      statusOptions: [{ label: '正常', key: 1 }, { label: '禁用', key: 0 }],
      temp: {
        id: undefined,
        name: '',
        username: '',
        password: '',
        status: 1,
        chat_amount: '',
        gift_rate: '',
        voice_amount: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      currentFirmId: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      firmList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total ? response.data.total : 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      this.listQuery.sort_field = data.prop
      this.listQuery.sort = this.listQuery.sort === 'asc' ? 'desc' : 'asc'
      this.handleFilter()
    },
    getSortClass: function() {
      this.listQuery.sort = this.listQuery.sort === 'asc' ? 'desc' : 'asc'
      return this.listQuery.sort === 'asc' ? 'ascending' : 'descending'
    },
    getFirmMoneyLog: function(item) {
      this.currentFirmId = item.id
      this.drawerVisibleMoney = true
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        username: '',
        password: '',
        status: 1,
        chat_amount: '',
        gift_rate: '',
        voice_amount: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createFirm(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '成功创建家族长',
              type: 'success',
              duration: 1500
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateFirm(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '成功编辑家族长',
              type: 'success',
              duration: 1500
            })
            this.getList()
          })
        }
      })
    }
  }
}
</script>

<style>
.click_a {
  color: #409EFF;
  padding-right: 5px;
}
.el-form-item__label{width: 150px !important;}
.el-form-item__content{margin-left: 150px !important;}
</style>

